package cqrtplm.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.classification.controller.TyplmClassificationController;
import com.hustcad.plm.pdm.classification.model.dto.TyplmClassificationEntityDTO;
import com.hustcad.plm.pdm.classification.service.TyplmClassificationService;
import com.hustcad.plm.pdm.file.handler.response.ResponseResult;
import com.hustcad.plm.pdm.folder.controller.TyplmProductFolderSearchController;
import com.hustcad.plm.pdm.folder.model.dto.filter.TySubFolderFilterQuery;
import com.hustcad.plm.pdm.folder.model.dto.filter.TyplmFolderObjDTO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.dto.PartNumberDTO;
import cqrtplm.dto.RtCfgMzDTO;
import cqrtplm.dto.RtCfgMzPartNumberDTO;
import cqrtplm.dto.TyplmClassificationEntityCopyDTO;
import cqrtplm.dto.query.RtCfgMzQueryDTO;
import cqrtplm.entity.RtCfgMzDO;
import cqrtplm.mapper.RTPartMapper;
import cqrtplm.mapper.RtCfgMzMapper;
import cqrtplm.service.IRtCfgMzService;
import cqrtplm.vo.RtCfgDspfDemandMainVO;
import cqrtplm.vo.RtCfgMzVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 模组管理Service业务层处理
 *
 * @author 江小熊
 * @date 2025-09-10
 */
@Service
public class RtCfgMzServiceImpl implements IRtCfgMzService
{
    @Resource
    private RtCfgMzMapper rtCfgMzMapper;
    @Resource
    private TyplmProductFolderSearchController typlmProductFolderSearchController;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private TyplmClassificationService typlmClassificationService;
    @Resource
    private RTPartMapper rtPartMapper;

    /**
     * 查询模组管理
     *
     * @param moduleid 模组管理主键
     * @return 模组管理
     */
    @Override
    public ResponseResult selectRtCfgMzByMODULEID(String moduleid)
    {
        RtCfgMzDO rtCfgMzDO = rtCfgMzMapper.selectRtCfgMzByMODULEID(moduleid);
        RtCfgMzVO rtCfgMzVO = new RtCfgMzVO();
        BeanUtil.copyProperties(rtCfgMzDO,rtCfgMzVO);
        String partslist = rtCfgMzVO.getPartslist();
        if(StrUtil.isNotEmpty(partslist)){
            List<RtCfgMzVO.partsVO> partsVOS = JSONUtil.toList(partslist, RtCfgMzVO.partsVO.class);
            rtCfgMzVO.setPartsVOs(partsVOS);
        }
        return ResponseResult.success(rtCfgMzVO,"请求成功");
    }

    /**
     * 查询模组管理列表
     *
     * @param rtCfgMz 模组管理
     * @return 模组管理
     */
    @Override
    public List<RtCfgMzDO> selectRtCfgMzList(RtCfgMzDO rtCfgMz)
    {
        return rtCfgMzMapper.selectRtCfgMzList(rtCfgMz);
    }

    /**
     * 新增模组管理
     *
     * @param
     * @return 结果
     */
    @Override
    public ResponseResult insertRtCfgMz(RtCfgMzDTO dto)
    {
        RtCfgMzDO rtCfgMz = new RtCfgMzDO();
        BeanUtil.copyProperties(dto,rtCfgMz);
        String partstr = JSONUtil.toJsonStr(dto.getPartsArr());
        rtCfgMz.setPartslist(partstr);
        String moduleid = snowflakeIdComponent.getInstance().nextId().toString();
        rtCfgMz.setModuleid(moduleid);
        rtCfgMz.setCreatetime(new Date());
        UserDO user = TyAccountContext.getUser();
        rtCfgMz.setCreateuser(user.getName());
        rtCfgMzMapper.insertRtCfgMz(rtCfgMz);
        return ResponseResult.success(moduleid,"请求成功");
    }

    /**
     * 修改模组管理
     *
     * @param dto 模组管理
     * @return 结果
     */
    @Override
    public ResponseResult updateRtCfgMz(RtCfgMzDTO dto)
    {
        RtCfgMzDO rtCfgMz = new RtCfgMzDO();
        BeanUtil.copyProperties(dto,rtCfgMz);
        if(IterUtil.isNotEmpty(dto.getPartsArr())){
            String jsonStr = JSONUtil.toJsonStr(dto.getPartsArr());
            rtCfgMz.setPartslist(jsonStr);
        }
        rtCfgMz.setUpdatetime(new Date());
        rtCfgMz.setUpdateuser(TyAccountContext.getUser().getName());
        rtCfgMzMapper.updateRtCfgMz(rtCfgMz);
        return ResponseResult.success("修改成功");
    }

    /**
     * 批量删除模组管理
     *
     * @param moduleids 需要删除的模组管理主键
     * @return 结果
     */
    @Override
    public ResponseResult deleteRtCfgMzByMODULEIDs(List<String> moduleids)
    {
        rtCfgMzMapper.deleteRtCfgMzByMODULEIDs(moduleids);
        return ResponseResult.success("删除成功");
    }

    /**
     * 删除模组管理信息
     *
     * @param MODULEID 模组管理主键
     * @return 结果
     */
    @Override
    public int deleteRtCfgMzByMODULEID(String MODULEID)
    {
        return rtCfgMzMapper.deleteRtCfgMzByMODULEID(MODULEID);
    }

    @Override
    public PageInfo<RtCfgMzVO> selectPageList(RtCfgMzQueryDTO queryDTO, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<RtCfgMzVO> list = rtCfgMzMapper.selectPageList(queryDTO);
        return new PageInfo<RtCfgMzVO>(list);
    }

    @Override
    public ResponseResult getModuleCodes() {
//        String jsonstr = "{\"subFolderOid\":\"747238704946495488\",\"subFolderOtype\":\"ty.inteplm.folder.CTySubFolder\",\"curPage\":1,\"pageSize\":20,\"needCount\":false,\"keyword\":\"\",\"subFolderFilterDTO\":{\"oid\":\"363292770112602112\",\"otype\":\"ty.inteplm.folder.CTyTableViewDescriptor\",\"name\":\"全部\",\"createstamp\":\"2022-11-21 23:21:09\",\"updatestamp\":\"2024-05-08 16:07:41\",\"modifystamp\":\"2024-05-08 16:07:41\",\"updatecount\":\"2\",\"markfordelete\":\"0\",\"identifierRef\":{\"oid\":\"363292770112602112\",\"otype\":\"ty.inteplm.folder.CTyTableViewDescriptor\"},\"containeroid\":\"251680307611926528\",\"containerotype\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"attributes\":\"All\",\"tableid\":\"folderbrowser_PDM\",\"system\":\"1\",\"published\":\"1\",\"owneroid\":\"105\",\"ownerotype\":\"ty.inteplm.org.CTyUser\",\"matchall\":\"1\",\"inheriteddomain\":\"0\",\"hidden\":\"0\",\"frozencolumns\":\"-1\",\"domainoid\":\"251680307620315136\",\"domainotype\":\"ty.inteplm.domain.CTyDomain\",\"viewgroup\":\"folder\",\"systemdefault\":1,\"searchCondition\":{\"typeList\":[],\"conditionJoint\":\"and\",\"conditionGroups\":[],\"pageNum\":1,\"pageSize\":20,\"needIBA\":false,\"columns\":[{\"propertyName\":\"changestatus\",\"displayName\":\"更改状况\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"graphical\",\"displayName\":\"图形标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"thumbnailFile\",\"displayName\":\"缩略图\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"120\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"identifier\",\"displayName\":\"标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"300\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"state\",\"displayName\":\"生命周期状态\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"typeDefName\",\"displayName\":\"类型\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifier\",\"displayName\":\"修改者\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifystamp\",\"displayName\":\"修改时间\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false}],\"needThumbnailFile\":false,\"searchType\":1},\"searchColumnList\":[{\"propertyName\":\"changestatus\",\"displayName\":\"更改状况\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"graphical\",\"displayName\":\"图形标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"thumbnailFile\",\"displayName\":\"缩略图\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"120\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"identifier\",\"displayName\":\"标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"300\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"state\",\"displayName\":\"生命周期状态\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"typeDefName\",\"displayName\":\"类型\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifier\",\"displayName\":\"修改者\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifystamp\",\"displayName\":\"修改时间\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false}],\"info\":{\"classDisplay\":\"\",\"typeDisplay\":\"所有类型\",\"contextDisplay\":\"所有上下文\",\"conditionDisplayList\":[],\"columnDisplay\":\"更改状况、图形标识、缩略图、标识、生命周期状态、类型、修改者、修改时间\"},\"createSystemView\":false,\"needReturnOptionColumn\":false,\"clazzDisplayName\":\"\",\"displayFullName\":\"全部\"}}";
//        TySubFolderFilterQuery tySubFolderFilterQuery = JSONUtil.toBean(jsonstr, TySubFolderFilterQuery.class);
//        com.ty.basic.response.ResponseResult<PageInfo<TyplmFolderObjDTO>> filter = typlmProductFolderSearchController
//                .getFolderObjectBySubfolderFilter(tySubFolderFilterQuery);
//        List<TyplmFolderObjDTO> list = filter.getData().getList();
//        if(IterUtil.isEmpty(list)){
//            ResponseResult.fail(RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("无需求模板数据，请联系管理员"),"无需求模板数据，请联系管理员");
//        }
//        List<String> modeuleCodes = list.stream()
//                // 提取number字段，这里假设number是数字类型，调用其toString()方法转为字符串
//                .map(dto -> dto.getNumber().toString())
//                // 收集为List<String>
//                .collect(Collectors.toList());

        List<PartNumberDTO> list = rtPartMapper.selectAllPart("状态需求模板");
        List<String> partNumbers = list.stream()
                .map(PartNumberDTO::getPartNumber) // 提取partNumber
                .collect(Collectors.toList());    // 收集成List

        return ResponseResult.success(partNumbers,"200");
    }

    @Override
    public ResponseResult getPlTrees() {

        List<Map<String,String>> list = rtCfgMzMapper.queryPartsByTypeAndNum();

//        List<TyplmClassificationEntityDTO> classificationEntityDTOS;
//        classificationEntityDTOS = typlmClassificationService.queryClassification("722793572393713664");
//        List<TyplmClassificationEntityCopyDTO> typlmClassificationEntityCopyDTOS = BeanUtil.copyToList(
//                classificationEntityDTOS, TyplmClassificationEntityCopyDTO.class);
//        List<TyplmClassificationEntityCopyDTO> list = this.buildFullTree(
//                typlmClassificationEntityCopyDTOS);
        return ResponseResult.success(list,"请求成功");
    }

    @Override
    public ResponseResult getMaterialCodeAndStandardComponent(RtCfgMzPartNumberDTO vo) {
        if (StrUtil.isBlank(vo.getNeedtemcode()) || Objects.isNull(vo)){
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("传入参数为空");
        }
        //当选择图号时  获取所有的有效图号
        if (vo.getNeedtemcode().equals("1")){
           return ResponseResult.success(rtCfgMzMapper.selectPartNumberByNumber(vo.getPartnumber(), RTPlmConstant.PATTERNCODE),"") ;
        }
        if (vo.getNeedtemcode().equals("0")){
            return ResponseResult.success(rtCfgMzMapper.selectPartNumberByNumber(vo.getPartnumber(), RTPlmConstant.MATERIALCODE),"") ;
        }
        return ResponseResult.success("");
    }

    /**
     * 构建完整的树形结构（从顶层节点到最底层子节点）
     * @param nodes 顶层节点列表（初始传入的根节点）
     * @return 完整的树形结构（包含所有层级的节点）
     */
    private List<TyplmClassificationEntityCopyDTO> buildFullTree(List<TyplmClassificationEntityCopyDTO> nodes) {
        // 空集合直接返回（避免空指针）
        if (IterUtil.isEmpty(nodes)) {
            return nodes;
        }
        // 遍历每个节点，为其填充子节点（递归处理）
        for (TyplmClassificationEntityCopyDTO currentNode : nodes) {
            // 1. 根据当前节点类型查询子节点数据（DTO）
            List<TyplmClassificationEntityDTO> childEntityList = getChildEntities(currentNode);

            // 2. 转换子节点为CopyDTO（与当前节点类型一致）
            List<TyplmClassificationEntityCopyDTO> childNodes = BeanUtil.copyToList(
                    childEntityList, TyplmClassificationEntityCopyDTO.class);

            // 3. 递归处理子节点（先为子节点填充它们的子节点）
            List<TyplmClassificationEntityCopyDTO> processedChildNodes = buildFullTree(childNodes);

            // 4. 为当前节点设置处理后的子节点（包含所有层级）
            currentNode.setChildNode(processedChildNodes);
        }

        // 返回当前节点列表（已包含所有层级的子节点）
        return nodes;
    }

    /**
     * 根据节点类型查询子节点数据（抽取重复逻辑）
     */
    private List<TyplmClassificationEntityDTO> getChildEntities(TyplmClassificationEntityCopyDTO node) {
        if ("ty.inteplm.type.CTyClassificationRoot".equals(node.getOtype())) {
            return typlmClassificationService.queryClassificationByRoot(node.getId());
        } else {
            return typlmClassificationService.queryClassification(node.getId());
        }
    }
}
